﻿using Game.Foundation;
using Bruce.Net;
using System;

namespace Server.Major
{
    /// <summary>
    /// 客户端消息分发器
    /// </summary>
    class ClientDispatcher : AbsDispatcher<IPacket>
    {
        protected override void Handle(IPacket item)
        {
            Packet packet = (Packet)item;

            try
            {
                PacketType type = (PacketType)packet.Protocol;
                switch (type)
                {
                    case PacketType.Pong:
                        break;

                    case PacketType.游戏列表请求包:
                        ProcessGameListRequest(packet);
                        break;

                    default:
                        Console.WriteLine("未找到对应的客户端协议。");
                        break;
                }
            }
            catch (System.IO.IOException)
            {
                Console.Beep();
                Console.Error.WriteLine("类型：{0}，OptionOne：{1}协议格式出错！", packet.Protocol, packet.OptionOne);
            }
        }

        private void ProcessGameListRequest(Packet p)
        {
            p.ClearBody();
            p.Protocol = (int)PacketType.游戏列表返回包;
            p.WriteInt32(Program.m_gameDict.Count);
            foreach (var gameserver in Program.m_gameDict.Values)
            {
                p.WriteString(gameserver.Name);
                p.WriteString(gameserver.IPAddress);
                p.WriteInt32(gameserver.Port);
                p.WriteInt32(gameserver.SeatCount);
                p.WriteString(gameserver.RelativePath);
                p.WriteString(gameserver.DownloadPath);

                p.WriteInt32(gameserver.AreaList.Count);
                foreach (GameAreaConfig area in gameserver.AreaList)
                {
                    p.WriteInt32(area.ID);
                    p.WriteString(area.Name);
                    p.WriteInt32(area.RoomList.Count);

                    foreach (GameRoomConfig room in area.RoomList)
                    {
                        p.WriteInt32(room.ID);
                        p.WriteString(room.Name);
                    }
                }
            }

            p.SendBySession();
        }
    }
}
